package cevent.source.cloudcenter.server.util;/**
 * Created by Cevent on 2021/4/28.
 */

import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Decoder;

import java.io.*;

/**
 * @author cevent
 * @description base64转为multipart文件File
 * @date 2021/4/28 14:02
 */
public class Base64ToMultipartFile implements MultipartFile{
    private final byte[] imageContent;
    private final String imageHeader;

    public Base64ToMultipartFile(byte[] imageContent, String imageHeader) {
        this.imageContent = imageContent;
        this.imageHeader = imageHeader.split(";")[0];
    }

    @Override
    public String getName() {
        return System.currentTimeMillis()+Math.random()+"."+imageHeader.split("/")[1];
    }

    @Override
    public String getOriginalFilename() {
        return System.currentTimeMillis()+ (int) (Math.random() * 10000) +"."+imageHeader.split("/")[1];
    }

    @Override
    public String getContentType() {
        return imageHeader.split(":")[1];
    }

    @Override
    public boolean isEmpty() {
        return imageContent==null || imageContent.length==0;
    }

    @Override
    public long getSize() {
        return imageContent.length;
    }

    @Override
    public byte[] getBytes() throws IOException {
        return imageContent;
    }

    @Override
    public InputStream getInputStream() throws IOException {
        return new ByteArrayInputStream(imageContent);
    }

    @Override
    public void transferTo(File dest) throws IOException, IllegalStateException {
        new FileOutputStream(dest).write(imageContent);
    }
    //base64字符串：文件说明+","+base64码(文件内容)
    public static MultipartFile base64TransToMultipartFile(String base64){
        try {
            //根据逗号,进行对传入的base64格式文件进行分隔
            String [] baseStrs=base64.split(",");
            BASE64Decoder decoder=new BASE64Decoder();
            byte[] bytes=new byte[0];
            //文件内容：baseStrs[1] 将bytes转换为multipartFile
            bytes=decoder.decodeBuffer(baseStrs[1]);

            for (int i=0;i<bytes.length;++i){
                if (bytes[i]<0){
                    bytes[i]+=256;
                }
            }
            //文件类型：baseStrs[0]
            return new Base64ToMultipartFile(bytes,baseStrs[0]);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
}
